package com.share.netdisk.garbage.controller;


import com.share.constant.Result;
import com.share.netdisk.garbage.service.GarbageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/file")
public class GarbageController {

	@Autowired
	private GarbageService garbageService;

	//文件批量恢复
	@PostMapping("/restore")
	public Result restore(@RequestParam(value = "reclaims", required = true) String reclaimIds) {
		if (reclaimIds == null || reclaimIds.trim().isEmpty()) {
			return Result.fail(400, "Parameter 'fileIds' is missing or empty", null);
		}

		try {
			// 将逗号分隔的字符串转换为整数列表，并处理可能的格式错误
			List<Integer> ids;
			try {
				ids = Arrays.stream(reclaimIds.split(","))
						.map(String::trim)
						.map(Integer::parseInt)
						.collect(Collectors.toList());
			} catch (NumberFormatException e) {
				return Result.fail(400, "Invalid file ID format: " + e.getMessage(), null);
			}

			// 调用服务层进行文件恢复
			Map<Integer, String> result = garbageService.restoreFilesByReclaimId(ids);

			if (result.isEmpty()) {
				return Result.ok("所有文件恢复成功");
			} else {
				// 构建失败信息
				String failedMessages = result.entrySet().stream()
						.map(entry -> "File ID " + entry.getKey() + ": " + entry.getValue())
						.collect(Collectors.joining("; "));
				return Result.fail(500, "部分文件恢复失败: " + failedMessages, null);
			}
		} catch (Exception e) {
			log.error("文件恢复过程中出现错误: {}", e.getMessage(), e);
			return Result.fail(500, "文件恢复过程中出现错误: " + e.getMessage(), null);
		}
	}
}
